from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from concurrent.futures import ThreadPoolExecutor
from app.utils.response import APIResponse
from app.utils.errors import ValidationError, NotFoundError, ServiceError
from app.utils.logger import setup_logger
from config.config import config
import os
import logging

# 初始化扩展
db = SQLAlchemy()
migrate = Migrate()

# 设置全局 logger
logger = logging.getLogger('app')

def create_app(config_name=None):
    """创建 Flask 应用"""
    app = Flask(__name__)
    
    # 加载配置
    if config_name is None:
        config_name = os.getenv('FLASK_CONFIG', 'development')
    
    # 加载基本配置
    app.config.from_object(config[config_name])
    
    # 初始化日志
    setup_logger(app)
    
    # 初始化配置
    config[config_name].init_app(app)
    
    # 验证 Ollama 配置
    ollama_config = app.config.get('OLLAMA', {})
    app.logger.info(f"Using Ollama config: {ollama_config}")
    
    # 初始化扩展
    db.init_app(app)
    migrate.init_app(app, db)
    
    # 初始化线程池执行器
    app.executor = ThreadPoolExecutor(
        max_workers=app.config.get('TASK', {}).get('max_workers', 4)
    )
    
    # 注册蓝图
    from app.api import bp as api_bp
    app.register_blueprint(api_bp, url_prefix='/api/v1')
    
    # 添加主页路由
    @app.route('/')
    def index():
        return render_template('index.html')
    
    # 添加错误处理
    @app.errorhandler(404)
    def not_found_error(error):
        if request.path.startswith('/api/'):
            return APIResponse.error('API endpoint not found', 404)
        return render_template('404.html'), 404
    
    @app.errorhandler(500)
    def internal_error(error):
        db.session.rollback()
        if request.path.startswith('/api/'):
            return APIResponse.error('Internal server error', 500)
        return render_template('500.html'), 500
    
    return app

from app import models 